﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QQ2564874169.Nubbo;

namespace Tests.Nubbo.Mocks
{
    class MockServer : INubboServer
    {
        public event EventHandler<ServiceRequest> NewRequest;

        public void OnNewRequest(MockInvoker invoker, string serviceName, RequestParam request)
        {
            var req = new ServiceRequest(serviceName, OnResponse, invoker);

            foreach (var key in request.Header.Keys)
            {
                req.Param.Header.Add(key, request.Header[key]);
            }
            foreach (var key in request.Param.Keys)
            {
                req.Param.Param.Add(key, request.Param[key]);
            }
            NewRequest?.Invoke(this, req);
        }

        private static void OnResponse(ServiceResult result, object state)
        {
            var invoker = (MockInvoker) state;

            var res = new ResponseResult
            {
                Error = result.Error
            };
            if (result.Data != null)
            {
                res.Data = new JsonOutput().Serialize(result.Data);
            }
            foreach (var key in result.Header.Keys)
            {
                res.Header.Add(key, result.Header[key]);
            }
            invoker.SetResult(res);
        }

        public void Start()
        {

        }

        public void Close()
        {

        }
    }
}
